<?php
declare (strict_types = 1);
/**
 * 管理员
 */
namespace app\common\admin;

use app\common\facade\model\AdminModel;
use app\common\facade\model\AdminRoleModel;
use app\common\facade\model\AdminRuleModel;

class Roles extends BaseAdmin
{
    /**
     * 角色添加编辑保存
     */
    public function roleAddEditSave($param = [])
    {
        $where = [];

        if(isset($param['id'])):
            $where[] = ['id', '=', $param['id']];
            unset($param['id']);
        endif;

        AdminRoleModel::addEditSave($param, $where);
        return true;
    }

    /**
     * 获取角色列表信息
     */
    public function rolesLists()
    {
        return AdminRoleModel::listsAll();
    }

    /**
     * 获取角色信息
     */
    public function rolesInfo($param = [])
    {
        $field = ['id', 'name', 'description', 'ruleId'];
        return AdminRoleModel::info($param, $field);
    }

    /**
     * 角色删除
     */
    public function rolesDelete($param = [])
    {
        if(empty($param['id'])) exception('删除失败！');
        $where = [['id', '=', $param['id']]];

        return AdminRoleModel::deleteData($where);
    }

    /**
     * 角色批量删除
     */
    public function rolesDeletes($param = [])
    {
        if(empty($param['idstr'])) exception('删除失败！');
        $where = [['id', 'in', $param['idstr']]];

        return AdminRoleModel::deleteData($where);
    }    

    /**
     * 角色下权限删除
     */
    public function roleRuleDel($roleid = 0, $ruleid = 0){
        if(empty($roleid) || empty($ruleid)) exception('删除失败，参数无效');

        // 1 查找角色对应ruleid 权限字段
        // 2 删除 指定$ruleid， 并查找对应栏目数组
        // 3 对栏目数组树形排序，并返回
        // 4 更新 角色权限；
        $roleRuleId = AdminRoleModel::info([['id', '=', $roleid]], 'ruleId')->ruleId;
        $ruleArr = array_diff(explode(',',$roleRuleId), [$ruleid]);
        
        $children = AdminRuleModel::field('id, pid, path, auth_name, enable')->where('id', 'in', $ruleArr)->select()->toArray();
        $data     = AdminRoleModel::treeRuleList($children);

        $upruleArr = AdminRoleModel::getTreeidStr($data); // 获取树形排序后的栏目id数组

        $res = AdminRoleModel::addEditSave(['ruleId' => implode(',' ,$upruleArr)] ,[['id', '=', $roleid]]);
        
        return $data;
    }
}